import Axios from 'axios'
import utils from './utils'
import router from '../router'
import {Message} from 'iview'

const baseURL = process.env.VUE_APP_SERVE + 'api'

Axios.defaults.baseURL = baseURL
// 请求拦截器
Axios.interceptors.request.use(function (config) {
    const token = utils.storeGet('token')
    if (token) {
        config.headers.token = token
    }
    return config
}, function (error) {
    return Promise.reject(error)
})

// 响应拦截器
Axios.interceptors.response.use((response) => {
    return response
}, (error) => {
    console.log(JSON.parse(JSON.stringify(error)))
    /*if (error.message === 'Network Error') {
        Message.error('服务端升级中')
    }*/
    const {response} = JSON.parse(JSON.stringify(error))
    if (response && response.data) {
        const data = response.data
        const status = response.status
        const {code, message} = data
        if (status === 500) {
            Message.error('系统错误')
        }
        if (code === 401 || code === 403) {
            Message.error(message)
        }
        if (code === 422) {
            console.log(data)
            for (let i of data.detail) {
                Message.error(i.message_cn || i.message)
            }
        }
        if (code === 401) {
            router.push('/login')
        }
        return Promise.reject(data)
    } else {
        return Promise.reject(error)
    }
})
export default Axios
